//
//  WMEClubCommentsViewController.m
//  everyDay_duiTang
//
//  Created by 恩叔 on 16/2/27.
//  Copyright © 2016年 enshu. All rights reserved.
//

#import "WMEClubCommentsViewController.h"
#import <UIImageView+WebCache.h>
#import <Masonry.h>
#import <AFNetworking.h>
#import "WMEClubCommentsTableViewCell.h"
#import <MJRefresh.h>
#import "WMEUserViewController.h"
#import "WMEClubReplyTableViewCell.h"
#import "WMELoginViewController.h"
#import "WMEFirstPageModel.h"
@interface WMEClubCommentsViewController ()<UITableViewDataSource, UITableViewDelegate, pushUserDelegate, pushUserViewDelegate>
@property (nonatomic, retain)UITableView *tableView;/**<主视图*/
@property (nonatomic, retain)UIView *headView;/**<头部视图*/
@property (nonatomic, retain)NSString *urlStr;/**<网络请求*/
@property (nonatomic, retain)NSMutableArray *clubDataArr;/**<数据数组*/
@property (nonatomic, retain)NSNumber *next_start;/**<下次请求起始位置*/
@end

@implementation WMEClubCommentsViewController

- (void)dealloc
{
    [_tableView release];
    [_headView release];
    [_urlStr release];
    [_clubDataArr release];
    [_next_start release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"";
    [self createHeadView];
    [self createTableView];
    [self data];
    if (_model.reply_count.integerValue > 25) {
        [self loadingFunction];
    }
    
}
- (void)createHeadView
{
    self.headView.userInteractionEnabled = YES;
    self.headView = [[UIView alloc] init];
    [self.view addSubview:_headView];
    [_headView release];
    
    UIImageView *userImg = [[UIImageView alloc] init];
    [self.headView addSubview:userImg];
    userImg.layer.cornerRadius = 20;
    userImg.clipsToBounds = YES;
//    __block __typeof(&*self)bs =self;
//    [userImg mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(bs.view.mas_left).with.offset(10);
//        make.top.equalTo(bs.view.mas_top).with.offset(10);
//        make.size.mas_equalTo(CGSizeMake(40, 40));
//    }];
    userImg.frame = CGRectMake(10, 10, 40, 40);
    [userImg sd_setImageWithURL:[NSURL URLWithString:_model.senderAvatar]];
    userImg.userInteractionEnabled = YES;
    UITapGestureRecognizer *userImgTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushUserViewAction:)];
    [userImg addGestureRecognizer:userImgTap];
    [userImg release];
    [userImgTap release];
    
    UILabel *userName = [[UILabel alloc] init];
    userName.textColor = [UIColor colorWithRed:0 green:160/255.0 blue:233/255.0 alpha:1];
    userName.text = _model.senderName;
    userName.font = [UIFont boldSystemFontOfSize:11];
    userName.userInteractionEnabled = YES;
    [self.headView addSubview:userName];
    UITapGestureRecognizer *userNameTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushUserViewAction:)];
    [userName addGestureRecognizer:userNameTap];
//    [userName mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(userImg.mas_right).with.offset(10);
//        make.right.equalTo(bs.view.mas_right).with.offset(-10);
//        make.top.equalTo(bs.view.mas_top).with.offset(10);
//        make.height.equalTo(@20);
//    }];
    userName.frame = CGRectMake(60, 10, WIDTH - 70, 20);
    [userName release];
    
    UILabel *time = [[UILabel alloc] init];
    time.textColor = [UIColor lightGrayColor];
    time.font = [UIFont systemFontOfSize:9];
    [self.headView addSubview:time];
//    [time mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(userImg.mas_right).with.offset(10);
//        make.right.equalTo(bs.view.mas_right).with.offset(-10);
//        make.top.equalTo(userName.mas_bottom).with.offset(0);
//        make.height.equalTo(@20);
//    }];
    time.text = [[self class] compareCurrentTime:_model.add_datetime_ts];
    time.frame = CGRectMake(60, 30, WIDTH - 70, 20);
    [time release];
    
    UILabel *content = [[UILabel alloc] init];
    [self.headView addSubview:content];
    content.text = _model.content;
    content.numberOfLines = 0;
    content.font = [UIFont systemFontOfSize:13];
    CGFloat contentHeight = [[self class] heightWithText:_model.content FontOfSize:13];
//    [content mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(userName.mas_right).with.offset(10);
//        make.right.equalTo(bs.view.mas_right).with.offset(-10);
//        make.top.equalTo(time.mas_bottom).with.offset(10);
//        make.height.equalTo(@(contentHeight));
//    }];
    content.frame = CGRectMake(60, 60, WIDTH - 70, contentHeight);
    [content release];
    if (![_model.path length]) {
        UILabel *line = [[UILabel alloc] init];
        line.frame = CGRectMake(60, content.frame.origin.y + content.frame.size.height + 20, WIDTH - 60, 0.3);
        line.backgroundColor = [UIColor lightGrayColor];
        [self.headView addSubview:line];
        [line release];
    }else {
        UIImageView *path = [[UIImageView alloc] init];
        path.frame = CGRectMake(60, content.frame.origin.y + content.frame.size.height + 20, 80, 80);
        [path sd_setImageWithURL:[NSURL URLWithString:_model.path]];
        path.contentMode = UIViewContentModeScaleAspectFill;
        path.clipsToBounds = YES;
        [self.headView addSubview:path];
        UILabel *line = [[UILabel alloc] init];
        line.frame = CGRectMake(60, path.frame.origin.y + path.frame.size.height + 20, WIDTH - 60, 0.3);
        line.backgroundColor = [UIColor lightGrayColor];
        [self.headView addSubview:line];
        [line release];
        [path release];
    }
    
}

- (void)createTableView
{
    self.tableView  = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    CGFloat contentHeight = [[self class] heightWithText:_model.content FontOfSize:13];
    if (![_model.path length]) {
        _headView.frame = CGRectMake(0, 0, WIDTH, contentHeight + 80);
    }else {
        _headView.frame = CGRectMake(0, 0, WIDTH, contentHeight + 80 + 100);
    }
    _tableView.tableHeaderView = _headView;
    [self.view addSubview:_tableView];
    __block __typeof(&*self)bs = self;
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bs.view.mas_left).with.offset(0);
        make.right.equalTo(bs.view.mas_right).with.offset(0);
        make.top.equalTo(bs.view.mas_top).with.offset(0);
        make.bottom.equalTo(bs.view.mas_bottom).with.offset(0);
    }];
    [_tableView release];
}
- (void)data
{
    NSString *temp = @"http://203.80.144.212/napi/topic/comment/reply/list/?platform_version=4.4.4&device_platform=L36h&__dtac=%257B%2522_r%2522%253A%2520%2522187455%2522%257D&t_comment_id=742928&screen_width=1080&screen_height=1776&__domain=www.duitang.com&app_version=67&start=0&platform_name=Android&locale=zh&app_code=nayutas";
    self.urlStr = [temp stringByReplacingOccurrencesOfString:@"t_comment_id=742928" withString:[NSString stringWithFormat:@"t_comment_id=%@", _model.repliesT_comment_id]];
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    [data GET:_urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        NSArray *arr = responseObject[@"data"][@"object_list"];
        self.next_start = responseObject[@"data"][@"next_start"];
        self.clubDataArr = [WMEClubInformationModel modelHandlerWithArray:arr];
        [_tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _clubDataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WMEClubInformationModel *model = _clubDataArr[indexPath.row];
    
    if (_clubDataArr.count != 0) {
        if (model.recipientId.integerValue > 0) {
            [_tableView registerClass:[WMEClubReplyTableViewCell class] forCellReuseIdentifier:@"replyCell"];
            WMEClubReplyTableViewCell *replyCell = [_tableView dequeueReusableCellWithIdentifier:@"replyCell" forIndexPath:indexPath];
            replyCell.model = model;
            replyCell.delegate = self;
            return replyCell;
            
        }else{
            [_tableView registerClass:[WMEClubCommentsTableViewCell class] forCellReuseIdentifier:@"commentsCell"];
            WMEClubCommentsTableViewCell *commentsCell = [_tableView dequeueReusableCellWithIdentifier:@"commentsCell" forIndexPath:indexPath];
            commentsCell.model = model;
            commentsCell.delegate = self;
            return commentsCell;
        }
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WMEClubInformationModel *model = _clubDataArr[indexPath.row];
        CGFloat height = [[self class] heightWithText:model.content FontOfSize:11];
        return height + 50;
}
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    //判断是否登陆 登陆后可以回复 回复完后 把数据添加进数组最后一行 (假的 下次网络请求不能显示)
////    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"success"]) {
//        UIAlertController *al = [UIAlertController alertControllerWithTitle:@"提示" message:@"还未开通评价功能" preferredStyle:UIAlertControllerStyleAlert];
//        //显示
//        [self presentViewController:al animated:YES completion:^{
//            // 一秒后执行diss方法
//            [self performSelector:@selector(diss:) withObject:self afterDelay:1];
//            
//        }];
////    }else{
//        WMELoginViewController *loginView = [[WMELoginViewController alloc] init];
//        [self presentViewController:loginView animated:YES completion:^{
//            
//        }];
////    }
//}


#pragma mark -加载

- (void)loadingFunction
{
    if (_model.reply_count.integerValue > _next_start.integerValue) {
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
//        // 设置了底部inset
//        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 30, 0);
//        // 忽略掉底部inset
//        self.tableView.mj_footer.ignoredScrollViewContentInsetBottom = 30;
    }
}
- (void)loadMoreData
{
    if (_model.reply_count.integerValue < _next_start.integerValue) {
        NSLog(@"数据已加载完成 不需要再加载");
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }else{
        NSString *newUrlStr = [_urlStr stringByReplacingOccurrencesOfString:@"start=0" withString:[NSString stringWithFormat:@"start=%@", _next_start]];
        AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
        [data GET:newUrlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@", responseObject);
            NSArray *arr = responseObject[@"data"][@"object_list"];
            self.next_start = responseObject[@"data"][@"next_start"];
            NSArray *tempArr = [WMEClubInformationModel modelHandlerWithArray:arr];
            [self.clubDataArr addObjectsFromArray:tempArr];
            [_tableView reloadData];
            if (_next_start.integerValue > _model.reply_count.integerValue) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            nil;
        }];
    }
}

//计算文本高
+ (CGFloat)heightWithText:(NSString *)text FontOfSize:(CGFloat )fontOfSize
{
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontOfSize]};
    //最大范围
    CGSize size = CGSizeMake(WIDTH - 110, 1000);
    //计算 文本 需的rectangular
    CGRect r = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    //返回文本 的 高
    return r.size.height;
}


//计算文本宽
+ (CGFloat)widthWithText:(NSString *)text MySize:(CGSize)size MyFontSize:(CGFloat)fontSize
{
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    //    CGSize size = CGSizeMake(WIDTH - 100, 10);
    CGRect r = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return r.size.width;
}

//计算时间 转换成 距离现在 多久
+ (NSString *)compareCurrentTime:(NSNumber *)date
{
    // 返回以1970/01/01 GMT为基准，然后过了secs秒的时间
    NSDate *compareDate = [NSDate dateWithTimeIntervalSince1970:[date doubleValue]];
    // 以当前时间(Now)为基准时间，返回实例保存的时间与当前时间(Now)的时间间隔
    NSTimeInterval  timeInterval = [compareDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    long temp = 0;
    NSString *result;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    }
    else if((temp = timeInterval / 60) < 60){
        result = [NSString stringWithFormat:@"%ld分钟前", temp];
    }
    
    else if((temp = temp / 60) < 24){
        result = [NSString stringWithFormat:@"%ld小时前", temp];
    }
    
    else if((temp = temp / 24) < 30){
        result = [NSString stringWithFormat:@"%ld天前", temp];
    }
    
    else if((temp = temp / 30) < 12){
        result = [NSString stringWithFormat:@"%ld月前", temp];
    }
    else{
        temp = temp / 12;
        result = [NSString stringWithFormat:@"%ld年前", temp];
    }
    
    return  result;
}

#pragma maek -pushUserViewAction
- (void)pushUserViewAction:(UITapGestureRecognizer *)tap
{
    NSString *userTemp = @"http://www.duitang.com/napi/people/profile/?__dtac=%257B%2522_r%2522%253A%2520%2522998121%2522%257D&_ts=1452865118.002704&app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=iPhone%205&device_platform=iPhone5%2C2&include_fields=relationship%2Cbind_status%2Cinterests%2Cidentity%2Ccity%2Ccitycode%2Cgender%2Cbirthday%2Crecommend_info%2Cclub_count&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=568&screen_width=320&user_id=11200118";
    NSString *userStr = [userTemp stringByReplacingOccurrencesOfString:@"11200118" withString:_model.senderId.stringValue];
    //AFN网络请求
    AFHTTPSessionManager *userData = [AFHTTPSessionManager manager];
    [userData GET:userStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"%@", responseObject);
        NSMutableDictionary *dic = responseObject[@"data"];
        WMEUserViewController *userVC = [[WMEUserViewController alloc] init];
        UINavigationController *userNavi = [[UINavigationController alloc] initWithRootViewController:userVC];
        userVC.userId = _model.selfId.stringValue;
        userVC.userDic = dic;
        [self presentViewController:userNavi animated:YES completion:^{
        }];
        [userVC release];
        [userNavi release];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
    

}
#pragma mark -协议方法 (pushUserView)
- (void)pushUserAction:(NSString *)string
{
    NSString *userTemp = @"http://www.duitang.com/napi/people/profile/?__dtac=%257B%2522_r%2522%253A%2520%2522998121%2522%257D&_ts=1452865118.002704&app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=iPhone%205&device_platform=iPhone5%2C2&include_fields=relationship%2Cbind_status%2Cinterests%2Cidentity%2Ccity%2Ccitycode%2Cgender%2Cbirthday%2Crecommend_info%2Cclub_count&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=568&screen_width=320&user_id=11200118";
    NSString *userStr = [userTemp stringByReplacingOccurrencesOfString:@"11200118" withString:string];
    //AFN网络请求
    AFHTTPSessionManager *userData = [AFHTTPSessionManager manager];
    [userData GET:userStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"%@", responseObject);
        NSMutableDictionary *dic = responseObject[@"data"];
        WMEUserViewController *userVC = [[WMEUserViewController alloc] init];
        UINavigationController *userNavi = [[UINavigationController alloc] initWithRootViewController:userVC];
        userVC.userId = string;
        userVC.userDic = dic;
        [self presentViewController:userNavi animated:YES completion:^{
        }];
        [userNavi release];
        [userVC release];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
}
- (void)pushUserView:(NSString *)str
{
    NSString *userTemp = @"http://www.duitang.com/napi/people/profile/?__dtac=%257B%2522_r%2522%253A%2520%2522998121%2522%257D&_ts=1452865118.002704&app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=iPhone%205&device_platform=iPhone5%2C2&include_fields=relationship%2Cbind_status%2Cinterests%2Cidentity%2Ccity%2Ccitycode%2Cgender%2Cbirthday%2Crecommend_info%2Cclub_count&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=568&screen_width=320&user_id=11200118";
    NSString *userStr = [userTemp stringByReplacingOccurrencesOfString:@"11200118" withString:str];
    //AFN网络请求
    AFHTTPSessionManager *userData = [AFHTTPSessionManager manager];
    [userData GET:userStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"%@", responseObject);
        NSMutableDictionary *dic = responseObject[@"data"];
        WMEUserViewController *userVC = [[WMEUserViewController alloc] init];
        UINavigationController *userNavi = [[UINavigationController alloc] initWithRootViewController:userVC];
        userVC.userId = str;
        userVC.userDic = dic;
        [self presentViewController:userNavi animated:YES completion:^{
        }];
        [userVC release];
        [userNavi release];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];

}
- (void)diss:(id)a
{
    [self dismissViewControllerAnimated:YES completion:^{
        [self dismissViewControllerAnimated:YES completion:^{
        }];
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
